package com.tddx.activiti.business.sys.controller.systuser;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.tddx.activiti.business.sys.entity.systuser.SysTuserEntity;
import com.tddx.activiti.business.sys.service.systuser.SysTuserService;
import com.tddx.activiti.business.sys.util.LoginUtil;
import com.tddx.activiti.business.sys.util.SysTuserUtil;
import com.tddx.activiti.common.Message;
import com.tddx.activiti.utils.DateUtils;
import com.tddx.activiti.utils.StringUtils;

@Controller
@RequestMapping("sys")
public class LoginCtrl {

	Logger log = Logger.getLogger(this.getClass());
	
	@Autowired SysTuserService service;
	
	@RequestMapping({ "login", "wxLogin"})
	public String login(SysTuserEntity entity, ModelMap map) {
		map.put("crrentdate", DateUtils.date2string("yyyy-MM-dd HH:mm"));
		if(SysTuserUtil.existUser()){
			map.put("user", SysTuserUtil.getCurrentUser());
			return "index";
		}
		if(StringUtils.isEmpty(entity.getVcUsername())
				||StringUtils.isEmpty(entity.getVcPass())){
			return "login";
		}
		String msg = LoginUtil.login(entity);
		map.put(Message.MESG, msg);
		if(msg.equals(Message.FAILED)){
			return "login";
		}
		map.put("user", SysTuserUtil.getCurrentUser());
		return "index";
	}
	
	@RequestMapping({ "register" })
	public String register(SysTuserEntity entity, String vcPassSure) {
		if(StringUtils.isNotEmpty(entity.getVcUsername())
				&&StringUtils.isNotEmpty(entity.getVcPass())
				&&vcPassSure.equals(entity.getVcPass())){
			try {
				entity.setVcName(entity.getVcUsername());
				service.save(entity);
			} catch (Exception e) {
				log.error(e);
				e.printStackTrace();
				return "register";
			}
			return "redirect:/sys/login.do";
		}else{
			return "register";
		}
	}

}
